package com.qf.air.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.qf.air.entity.Air;
import com.qf.air.enums.AirEnum;
import com.qf.air.exception.AirEx;
import com.qf.air.mapper.AirMapper;
import com.qf.air.service.AirService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: llf
 * @Date: 2021/11/4 21:02
 */
@Service
public class AirServiceImpl implements AirService {

    private String index = "air";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AirMapper airMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void save(Air air) {
        Integer count = airMapper.save(air);
        if(count !=1){
            //添加失败，记录日志，抛出异常
            System.out.println("添加信息失败！ air="+air);
            throw new AirEx(AirEnum.AIR_ADD_ERROR);
        }
        Air air1 = airMapper.selectById(air.getId());
        restTemplate.postForEntity("http://localhost:8079/air/add",air1,Air.class);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout = -1,readOnly = false,rollbackFor = Exception.class,noRollbackFor = ArithmeticException.class)
    public void deleteById(Integer id) {
        int i = airMapper.deleteById(id);
        if(i!=1){
            System.out.println("删除失败！ id="+id);
            throw new AirEx(AirEnum.AIR_DELETE_ERROR);
        }
        restTemplate.delete("http://localhost:8079/air/delete/{1}",id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateById(Air air) {
        int count = airMapper.updateById(air);
        if(count!=1){
            System.out.println("修改失败！ air="+air);
            throw new AirEx(AirEnum.AIR_UPDATE_ERROR);
        }
        Air air1 = airMapper.selectById(air.getId());
        restTemplate.postForEntity("http://localhost:8079/air/update", air1,Air.class);
    }
}
